﻿using System;
using System.IO;
using System.Linq;
using CmdTailCmd;
using regxExtensions;
using System.Diagnostics.CodeAnalysis;

namespace regx
{
    public class SearchFilterParams : RegxParams, ICmdTailCommand
    { // =======================================================================
        public bool IsValid(CmdTailContext ctx)
        { //-------------------------------------------------------------------
            return (File.IsEmpty() && Url.IsEmpty() && Pattern != null);
        }

        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "stdin", Justification = "stdin *is* spelled correctly")]
        public bool Execute(object o) 
        { //-------------------------------------------------------------------
            if (!InitializeExecution(Sources.Single)) return false;

            ErrorLevel           el  = o as ErrorLevel;
            RegexResultFormatter rrf = MakeFormatter();
            
            if (Debug)
            {
                // Show regex and output info
                _searcher.DebugOut();
                rrf.DebugOut();

                Console.WriteLine("Searching stdin as a filter");
                
                el.Set(ErrorLevelValue.NoError);
                return true;
            }

            el.Set(ErrorLevelValue.NoMatch);
            Stream stm = Console.OpenStandardInput();
            foreach (LineMatches lm in _searcher.MatchResults(stm))
            {
                if (lm.Matches.Count > 0) el.Set(ErrorLevelValue.Matched);
                // rrf.ProcessLineMatches(lm, line => Console.WriteLine(line)); // People thought this was more opaque than the foreach
                foreach (string line in rrf.FormatLineMatches(lm)) Console.WriteLine(line);
            }

            return true;
        }
    }
}